package com.yn.method;

import org.objectweb.asm.*;

public class CheckAndSetAsm {
    private int f;

    public void checkAndSetF(int f) {
        ClassWriter cw = new ClassWriter(0);
        MethodVisitor mv;

        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "checkAndSetF", "(I)V", null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ILOAD, 1);

        /**
         * 对应iflt 12
         */
        Label label0 = new Label();
        mv.visitJumpInsn(Opcodes.IFLT, label0);
        // aload 0
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        // iload 1
        mv.visitVarInsn(Opcodes.ILOAD, 1);
        // putfield
        mv.visitFieldInsn(Opcodes.PUTFIELD, "com/yn/method/CheckAndSet", "f", "I");


        Label l1 = new Label();
        mv.visitJumpInsn(Opcodes.GOTO, l1);

        mv.visitLabel(label0);
        mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
        mv.visitTypeInsn(Opcodes.NEW, "java/lang/IllegalArgumentException");
        mv.visitInsn(Opcodes.DUP);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/IllegalArgumentException", "<init>", "()V", false);
        mv.visitInsn(Opcodes.ATHROW);
        mv.visitLabel(l1);
        mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(2, 2);
        mv.visitEnd();
    }
}
